﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SingletonDemo
{
    /// <summary>
    /// 
    /// </summary>
    public class Singleton
    {
        /// <summary>
        /// 在定义变量时直接实例化对象（饿汉模式）
        /// </summary>
        private static Singleton _singleton = new Singleton();

        /// <summary>
        /// 
        /// </summary>
        private Singleton()
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static Singleton Instance()
        {
            return _singleton;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public string GetName()
        {
            return "zhangsan";
        }
    }



    public class Singleton2
    {
        /// <summary>
        /// 在定义变量时直接实例化对象（饿汉模式）
        /// </summary>
        private static Singleton2 _singleton = null;

        /// <summary>
        /// 
        /// </summary>
        private Singleton2()
        {
        }

        private static object obj = new object();

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static Singleton2 Instance()
        {
            if (_singleton == null)
            {
                lock (obj)//线程锁
                {
                    //临界区代码。  将对象的实例化工作推迟到调用时
                    if (_singleton == null)
                    {
                        _singleton = new Singleton2();
                    }
                }
            }
            return _singleton;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public string GetName()
        {
            return "lisi";
        }
    }
}
